// 提取 ID
// function extractIds(items = []) {
//   items = Array.isArray(items) ? items : [items]
//   return items.map(function(item) {
//     return item.id
//   })
// }

// 只合并新元素
function smartConcat(source, target, overwrite) {
  if (overwrite) return target
  source.GoodsData && source.GoodsData.push(...target.GoodsData)
  return source
}

export default function(apiConfig = {}) {
  const initialState = Object.assign({
    isLoading: 'NO',
    data: '',
    hasMore: true,
    message: '',
    params: {},
    state: ''
  }, apiConfig.initialState)

  return function(state, action) {
    let overwrite = (action.params || {})._overwrite
    let currentPage
    let data
    let hasMore

    switch (action.type) {
      case `REQUEST_${apiConfig.state}`:
        data = overwrite ? initialState.data : state.data;
        return Object.assign({}, state, { isLoading: 'YES', data });
      case `RECIEVE_${apiConfig.state}`: {
        data = smartConcat(
          state.data,
          action.data,
          overwrite !== undefined ? overwrite : true
        );

        hasMore = function() {
          const newFetchedData = action.data || [];
          const totalNum = newFetchedData.TotalNumber;

          if( parseInt(action.params.StartIndex)+8 < parseInt(totalNum) ){
            return true;
          }else{
            return false;
          }
        };

        return Object.assign({}, state, {
          isLoading: 'NO',
          data,
          hasMore: hasMore(),
          message: action.message,
          params: action.params,
          state: apiConfig.state
        })
      }
      default:
        return state || initialState;
    }
  }
}
